import numpy as np
import os
import pandas as pd
os.chdir('C:/Users/admin/Desktop')
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
pd.set_option('mode.chained_assignment', None)
f = pd.read_csv('otu_table_tax.txt',header=0,sep='\t',error_bad_lines=False,index_col=0)
g = f.drop(['taxonomy'],axis=1)
g['Col_sum'] = g.apply(lambda x: x.sum(), axis=1)
g = g.sort_values(by='Col_sum',ascending=False)
g = g.drop(['Col_sum'],axis=1)
g.loc[:,'taxonomy'] = f['taxonomy']
taxName = pd.DataFrame((';'.join(x.split('; ')[0:2]) for x in g['taxonomy']),index = g.index,columns = ['tax_name'])
taxLevelName = [x.split(';')[-1] for x in taxName['tax_name']]
taxLevel = [x.split('__')[0] for x in taxLevelName]
taxName = [x.split('__')[-1] for x in taxLevelName]
tax_level_name = pd.DataFrame({'tax_level':taxLevel,'Taxonomy':taxName},index=g.index)
tax_level_name=tax_level_name[~tax_level_name['tax_level'].isin(['k'])]
tax_level_name=tax_level_name.head(20)
df = pd.merge(tax_level_name,g,on='OTU ID')
f1 = pd.DataFrame(df, columns=['Taxonomy', 'taxonomy'])
f1.to_csv('taxonomy.txt',sep='\t')
f2 = df.drop(['tax_level','taxonomy','Taxonomy'],axis=1)
f2.to_csv('otu_table.txt',sep='\t')
